package com.nine.pattern.factory.config_factory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

/**
 * @author nine
 * @version 1.0
 * @description TODO
 * @date 2024-07-01 23:21
 */
public class CoffeeFactory {

	// 加载配置文件，获取配置文件中的类名，创建对象，放入map中
	// 1. 定义容器
	private static HashMap<String, Coffee> map = new HashMap<>();

	static {
		// 2. 加载配置文件，只加载一次
		Properties p = new Properties();
		InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
		try {
			p.load(is);
			p.keySet().forEach(key -> {
				String className = p.getProperty((String) key);
				// 反射获取对象
				Class clazz = null;
				try {
					clazz = Class.forName(className);
					Coffee coffee = (Coffee) clazz.newInstance();
					map.put((String) key, coffee);
				}
				catch (Exception e) {
					throw new RuntimeException(e);
				}
			});
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 根据名称获取对象
	 * @param name
	 * @return
	 */
	public static Coffee createCoffee(String name) {
		Coffee coffee = map.get(name);
		return coffee;
	}

}
